package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class AddressController {
    @Autowired
    private AddressService addressService;
    //查询地址
    @GetMapping("/address/list")
    public ResultInfo findList(){
        //调用service
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }
    //添加地址
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address){
        //调用service
        addressService.save(address);
        return ResultInfo.success(null);
    }
    //修改默认地址
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody Map<String,Long> map){
        //接收参数
        Long id = map.get("id");
        //调用service
        Address address=addressService.setDefault(id);
        return ResultInfo.success(address);
    }
    //查询默认地址
    @GetMapping("/address/default")
    public ResultInfo findDefault(){
        //调用service
        Address address=addressService.findDefault();
        if (address != null){
            return ResultInfo.success(address);
        }else {
            return ResultInfo.error("没有默认地址");
        }
    }
    //地址id回显查询
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id")Long id){
        //调用service
        Address address=addressService.findById(id);
        return ResultInfo.success(address);
    }
    //更新地址
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address){
        //调用service
        addressService.update(address);
        return ResultInfo.success(null);
    }
    //删除地址
    @DeleteMapping("/address")
    public ResultInfo deleteById( Long ids){
        //调用service方法
        addressService.deleteById(ids);
        return ResultInfo.success(null);
    }
}
